import os
import time
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

class ReportGenerator:
    def __init__(self):
        self.storage_path = os.getenv('STORAGE_PATH', './reports')
        os.makedirs(self.storage_path, exist_ok=True)
    
    def generate_report(self, data, platform):
        """生成报告文件"""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        # 修改为直接调用generate_docx方法
        filename = self.generate_docx(data, platform)
        return filename
    
    def generate_markdown(self, data, platform):
        """生成Markdown格式报告"""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{self.storage_path}/{platform}_report_{timestamp}.md"
        
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(f"# {platform}热点分析报告\n\n")
            f.write(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write("## 分析结果\n\n")
            f.write(data)
        
        return filename
    
    def generate_docx(self, analysis_data, platform_name):
        """生成Word格式报告"""
        doc = Document()
        
        # 添加标题（使用更简洁的格式）
        title = doc.add_paragraph()
        title_run = title.add_run(f'{platform_name}热点分析报告')
        title_run.font.size = Pt(16)
        title_run.bold = True
        title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        
        # 添加生成时间（简化格式）
        time_para = doc.add_paragraph()
        time_run = time_para.add_run(f'生成时间: {time.strftime("%Y-%m-%d %H:%M:%S")}')
        time_run.font.size = Pt(12)
        
        # 添加分隔线
        doc.add_paragraph("_"*50)
        
        # 处理分析数据
        if isinstance(analysis_data, str):
            # 去除Markdown符号
            clean_text = analysis_data.replace('*', '').replace('#', '')
            doc.add_paragraph(clean_text)
        else:
            # 添加热点事件（优化排版）
            if 'data' in analysis_data:
                doc.add_paragraph('热点排行:', style='Heading 2')
                for item in analysis_data['data']:
                    para = doc.add_paragraph(style='List Bullet')
                    run = para.add_run(f"{item.get('rank', '')}. {item.get('title', '')}")
                    run.font.size = Pt(12)
                    if item.get('hot'):
                        run.add_text(f" (热度: {item.get('hot')})")
                    if item.get('link'):
                        para.add_run().add_break()
                        link = para.add_run(f"链接: {item.get('link')}")
                        link.font.color.rgb = RGBColor(0x00, 0x00, 0xFF)
        
        # 保存文件
        reports_dir = os.getenv('STORAGE_PATH', './reports')
        os.makedirs(reports_dir, exist_ok=True)
        filename = f"{platform_name}_report_{time.strftime('%Y%m%d_%H%M%S')}.docx"
        filepath = os.path.join(reports_dir, filename)
        doc.save(filepath)
        
        return filepath

if __name__ == '__main__':
    generator = ReportGenerator()
    # 测试用示例数据
    test_result = "这是测试分析结果"
    report_file = generator.generate_markdown(test_result, '测试平台')
    print(f"报告已生成: {report_file}")